package com.jzdjt.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jzdjt.entity.UserEntity;
import com.jzdjt.tool.DBUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class LoginServlet extends HttpServlet {

	public LoginServlet() {
		super();
	}

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("UTF-8");
		// 根据标示名获取JSP文件中表单所包含的参数
		String userName = request.getParameter("username");
		String password = request.getParameter("password");
		System.out.println("userName:" + userName + "====password:" + password);

		String result = getStudent(userName, password);
		PrintWriter out = response.getWriter();// 回应请求
		out.write(result);
		out.flush();
		out.close();
		System.out.println(result);
	}

	private String getStudent(String username, String password) {
		try {
			JSONArray array = new JSONArray();
			JSONObject jsonObject = new JSONObject();
			String getStudentSql = "select * from Student where phoneNumber='" + username + "'";
			boolean loginStaute = false;
			String data = "";
			DBUtil dbUtil = new DBUtil();
			List<UserEntity> stulist = dbUtil.QueryFromStudent(getStudentSql);

			System.out.println("stulist.size():" + stulist.size());
			if (stulist != null && stulist.size() == 1) {
				UserEntity stu = stulist.get(0);

				if (stu != null) {
					String psw = stu.getPassword();
					System.out.println("psw>" + psw + "===password>" + password);
					if (psw != null) {
						if (psw.equals(password)) {
							loginStaute = true;
							array = JSONArray.fromObject(stu);
							data = "登录成功";
							// GRADEINFO = stu.getGrade();
							System.out.println(data);

						} else {
							data = "用户名或密码错误（密码错误）！";
							System.out.println("psw>" + psw + "===password>" + password);
							System.out.println("getstudentInfo: 用户名或密码错误（密码错误）！");
						}

					} else {
						data = "账户异常（密码为空）！";
						System.out.println("getstudentInfo: 账户异常（密码为空）！");
					}
				}
			} else {
				data = " 用户名或密码错误（用户名不正确）！";
				System.out.println("getstudentInfo: 用户名或密码错误（用户名不正确）！");
			}
			jsonObject.put("contents", array);
			// jsonObject.put("msginfo", data);
			// jsonObject.put("stats", loginStaute);
			return array.toString();
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println(e.getMessage());
			return "";

		}

	}

}